﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.IO;
using LeadExpress.Models.ViewPages;

namespace LeadExpress.Areas.MyAccount.Controllers
{
    public class ProductListController : Controller
    {
        private static string fileName = "";
        public static string staFileName
        {
            get { return fileName; }
            set { fileName = value; }
        }

        // Create an instance of user manage
        LeadExpress.Repository.ProductManagementRepository repository = new LeadExpress.Repository.ProductManagementRepository();
        public static string ProductImagesURL = ConfigurationManager.AppSettings["ProductImagesURL"].ToString();

        // GET: /Management/Home/
        [Authorize(Roles = "ClientAdmin")]
        public ActionResult Index()
        {
            // Get User ID
            ProductManagementModel model = new ProductManagementModel();

            var user = new Repository.UserRepository().GetSingle(User.Identity.Name);
            model = repository.GetModelByUser(user.ID, Helpers.Constant.HOME, "ClientAdmin", 10, 1);

            return View(model);
        }

        // GET: /Management/Product/Search?keywords=tt&fieldName=type
        [Authorize(Roles = "ClientAdmin")]
        public ActionResult Search(string keywords, string fieldName)
        {
            ProductManagementModel model = new ProductManagementModel();

            var user = new Repository.UserRepository().GetSingle(User.Identity.Name);
            model = repository.GetModelByUser(user.ID, Helpers.Constant.HOME, "ClientAdmin", keywords, fieldName, 10, 1);
            model.Keywords = keywords;
            model.FieldName = fieldName;

            return View(model);
        }


        [HttpPost]
        [Authorize(Roles = "ClientAdmin")]
        public ActionResult Fillter(string keywords, string startDate, string endDate, string categoryId, string stateId, int pageSize, int pageIndex, int id, string sortBy, string sortOrder)
        {
            ProductManagementModel model = new ProductManagementModel();

            var user = new Repository.UserRepository().GetSingle(User.Identity.Name);
            string[] categories = categoryId.Split(',');
            string[] states = stateId.Split(',');

            model = repository.GetModelByUser(user.ID, Helpers.Constant.HOME, "ClientAdmin", keywords, startDate, endDate, categories, states, sortBy, sortOrder, pageSize, pageIndex, id);

            return Json(model);
        }


        [HttpPost]
        [Authorize(Roles = "ClientAdmin")]
        public ActionResult SearchFillter(string keywords, string fieldName, int pageSize, int pageIndex)
        {
            ProductManagementModel model = new ProductManagementModel();
            model = repository.GetModelSearch(keywords, fieldName, pageSize, pageIndex);
            model.Keywords = keywords;
            model.FieldName = fieldName;

            return Json(model);
        }

        // GET: /Management/Home/
        [Authorize(Roles = "ClientAdmin")]
        public ActionResult Add()
        {
            ProductManagementModel model = new ProductManagementModel();
            model = repository.GetModel(Helpers.Constant.HOME, "ClientAdmin", 0);

            return View(model);
        }

        // GET: /Management/Home/
        [Authorize(Roles = "ClientAdmin")]
        public ActionResult PrintPage(int id)
        {
            ProductPrintModel model = new ProductPrintModel();
            model = repository.GetModelPrint(Helpers.Constant.HOME, "ClientAdmin", id);

            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        [Authorize(Roles = "ClientAdmin")]
        public ActionResult Add(FormCollection form)
        {
            var user = new Repository.UserRepository().GetSingle(User.Identity.Name);
            // Create product
            Product model = new Product();

            model.GUID = Guid.NewGuid().ToString();
            model.Title = form["Title"].ToString();
            model.ShortDesc = form["ShortDesc"].ToString();
            model.LongDesc = form["LongDesc"].ToString();
            model.MetaKeywords = form["MetaKeywords"].ToString();
            model.MetaDescription = form["MetaDescription"].ToString();
            model.ShowAllCategories = (form["AllCategories"] != null && form["AllCategories"].ToString() == "on");
            model.CategoryID = (form["CategoryID"] != null) ? int.Parse(form["CategoryID"].ToString()) : 0;
            model.SubCategoryID = (form["SubCategoryID"] != null) ? int.Parse(form["SubCategoryID"].ToString()) : 0;
            model.ShowAllStates = (form["AllStates"] != null && form["AllStates"].ToString() == "on");
            model.StateID = (form["StateID"] != null) ? form["StateID"].ToString() : null;
            model.DistrictID = (form["DistrictID"] != null) ? int.Parse(form["DistrictID"].ToString()) : 0;
            model.CreatedByUserID = user.ID;
            model.StartDate = DateTime.Now;
            model.EndDate = DateTime.Now.AddMonths(2);
            model.Active = (form["Active"] != null && form["Active"].ToString() == "on");

            repository.Create(model);

            // Check if product sucess
            if (model.ID > 0)
            {
                var transaction = (form["AcceptPayment"] != null && form["AcceptPayment"].ToString() == "on");

                if (transaction)
                {
                    Repository.ProductTransactionManagementRepository ptRepository = new Repository.ProductTransactionManagementRepository();
                    ProductTransaction ptModel = new ProductTransaction();

                    ptModel.ProductID = model.ID;
                    ptModel.ProductName = model.Title;
                    ptModel.OptionID = int.Parse(form["OptionID"].ToString());
                    ptModel.PaymentID = int.Parse(form["PaymentID"].ToString());

                    // Get option
                    var option = new Repository.ProductOptionManagementRepository().GetSingle(ptModel.OptionID.Value);
                    ptModel.ListPrice = option.Price;
                    ptModel.UnitPrice = option.UnitPrice;
                    ptModel.StartDate = DateTime.Now;
                    ptModel.EndDate = (option.LongTimeUnit.ToUpper() == "DAY") ? DateTime.Now.AddDays(option.LongTimeValue.Value) : DateTime.Now.AddMonths(option.LongTimeValue.Value);
                    ptModel.TransactionGuid = Guid.NewGuid().ToString();

                    // Get payment
                    var payment = new Repository.PaymentManagementRepository().GetSingle(ptModel.PaymentID.Value);
                    ptModel.PaymentName = payment.Name;

                    // Create transaction
                    ptRepository.Create(ptModel);
                }
                
            }

            return Redirect(string.Format("/MyAccount/ProductList/PrintPage/{0}", model.ID));
        }

        [Authorize(Roles = "ClientAdmin")]
        public ActionResult Edit(int id)
        {
            ProductManagementModel model = new ProductManagementModel();
            model = repository.GetModel(Helpers.Constant.HOME, "ClientAdmin", id);

            ViewBag.ProductId = id;

            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        [Authorize(Roles = "ClientAdmin")]
        public ActionResult Edit(int id, FormCollection form)
        {
            Product model = repository.GetSingle(id);

            if (model != null)
            {

                model.Title = form["Title"].ToString();
                model.ShortDesc = form["ShortDesc"].ToString();
                model.LongDesc = form["LongDesc"].ToString();
                model.MetaKeywords = form["MetaKeywords"].ToString();
                model.MetaDescription = form["MetaDescription"].ToString();
                model.Active = (form["Active"] != null && form["Active"].ToString() == "on");

                repository.Update(model);
            }

            return RedirectToAction("Index", "ProductList");
        }

        //[HttpPost]
        public ActionResult Upload(HttpPostedFileBase fileData)
        {
            // Verify that the user selected a file
            UserModel model = new UserModel();
            if (fileData != null && fileData.ContentLength > 0)
            {
                // extract only the fielname
                fileName = Path.GetFileName(fileData.FileName);

                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath(ProductImagesURL), fileName);
                fileData.SaveAs(path);
            }
            // redirect back to the index action to show the form once again
            return Json(model);
        }

        [HttpGet]
        [Authorize(Roles = "ClientAdmin")]
        public ActionResult UploadComplete()
        {
            return Json(string.Format("{0}/{1}", ProductImagesURL, fileName), JsonRequestBehavior.AllowGet);
        }
    }
}
